package model;

import java.util.List;


public class Agent {
	
	private double totalPayoff;
	public FIFOQueue history;
	public double threshold;
	public double reputation;
	
	public Agent(double threshold, int historySize) {
		this.threshold = threshold;
		history = new FIFOQueue(historySize);
		fillHistory(historySize);
		reputation = getReputation();
	}
	
	private void fillHistory(int historySize) {
		for(int i = 0; i < historySize; i++) {
			// Normal varians starting reputation +- 10%.
			if(0.4 + Math.random() * (0.6 - 0.4) > 0.5)
				history.Push(StrategyType.cooperator);
			else
				history.Push(StrategyType.defector);
		}
	}

	public double getReputation() {
		double cooperators = 0;
		double defectors = 0;
		
		for(int i = 0; i < history.size; i++) {
			if (history.c[i] == StrategyType.cooperator)
				cooperators++;
			else if(history.c[i] == StrategyType.defector)
				defectors++;
		}
		
		if (cooperators != 0)
			return cooperators / (cooperators+defectors);
		else
			return 0.0;
	}

	public StrategyType determineStragedy(List<Agent> agentList) {
		double cooperators = 0;
		double count = 0;
		
		// Iterates through the list of Agents counting their accumulated cooperations and defections.
		for (Agent a : agentList) {
			for(int i = 0; i < a.history.size; i++) {
				if (a.history.c[i] == StrategyType.cooperator) {
					cooperators++;
					count++;
				}
				else if(a.history.c[i] == StrategyType.defector) {
					count++;
				}
			}
		}
		if((cooperators/count) > threshold)
			return StrategyType.cooperator;
		else
			return StrategyType.defector;
	}
	
	public void pay(double cost){
		this.totalPayoff -= cost;
		}

	public double getPayoff(){
		return this.totalPayoff;
	}
	
	public void resetPayoff(){
		totalPayoff = 0;
	}

	public void reward(double payoff){
		this.totalPayoff += payoff;
	}


}

